package org.goldfish.message_board01.services;

import org.goldfish.message_board01.dao.MessageDetailDAO;
import org.goldfish.message_board01.dao.MessagePreviewDAO;
import org.goldfish.message_board01.entity.MessageDetail;
import org.goldfish.message_board01.entity.MessagePreview;

import java.time.LocalDateTime;
import java.util.List;

public class MessageService extends AbstractService{
    private final MessagePreviewDAO messagePreviewDAO;
    private final MessageDetailDAO messageDetailDAO;

    public MessageService() {
        this.messagePreviewDAO = new MessagePreviewDAO();
        this.messageDetailDAO = new MessageDetailDAO();
        addDAO(messagePreviewDAO);
        addDAO(messageDetailDAO);
    }

    /**
     * Fetch all message previews.
     *
     * @return List of MessagePreview objects.
     */
    public List<MessagePreview> getAllMessagePreviews() {
        return messagePreviewDAO.getAllMessages();
    }

    /**
     * Get detailed content of a specific message.
     *
     * @param messageId ID of the message.
     * @return List of MessageDetail objects representing each line of the message.
     */
    public List<String> getMessageDetails(int messageId) {
        return messageDetailDAO.getMessageContent(messageId);
    }

    public boolean addMessage(String sender, String title, String content) {
        if (title == null || title.isEmpty() || content == null || content.trim().isEmpty()) {
            return false;
        }

        // Split the content into multiple lines
        String[] lines = content.split("\n");
        for(int i = 0; i < lines.length; i++) {
            lines[i] = lines[i].replace("\r", ""); // Remove carriage return characters
        }

        // Create the message preview
        MessagePreview messagePreview = new MessagePreview();
        messagePreview.setSender(sender);
        messagePreview.setTitle(title);
        messagePreview.setPreview(lines.length > 0 ? lines[0] : ""); // Set the preview to the first line if available
        messagePreview.setTime(LocalDateTime.now());
        int id = messagePreviewDAO.insertMessagePreviewAndGetId(messagePreview);
        if (id == -1) {
            return false;
        }
        messagePreview.setId(id);
        // Add the message details
        int messageId = messagePreview.getId(); // Get the ID of the newly inserted message
        for (int i = 0; i < lines.length; i++) {
            MessageDetail detail = new MessageDetail(messageId, i + 1, lines[i]);
            if (!messageDetailDAO.insertMessageDetail(detail))
                return false;
        }

        return true;
    }
    public void destroy() {
        messagePreviewDAO.destroy();
        messageDetailDAO.destroy();
    }

}
